package com.cci.kangdao.service.impl;


import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cci.kangdao.utilTool.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.common.RedisKeys;
import com.cci.kangdao.dao.CompanyTDao;
import com.cci.kangdao.dao.DictionariesTDao;
import com.cci.kangdao.dao.GMApplyRecordTDao;
import com.cci.kangdao.dao.GMVisitorDao;
import com.cci.kangdao.dao.GMVisitorEntity;
import com.cci.kangdao.dao.LoginDao;
import com.cci.kangdao.dao.RelationShipTDao;
import com.cci.kangdao.dao.ServiceStationDao;
import com.cci.kangdao.dao.UserTDao;
import com.cci.kangdao.dao.model.CompanyT;
import com.cci.kangdao.dao.model.RelationShipT;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.enums.GMApplyRecordStatus;
import com.cci.kangdao.message.MessagePushUtils;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.GMApplyRecordFlowService;
import com.cci.kangdao.service.GMApplyRecordTService;
import com.cci.kangdao.service.GMApplyService;
import com.cci.kangdao.service.PropertiesUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;


//GM申请记录接口实现类
@Service("GMApplyRecordTService")
public class GMApplyRecordTServiceImpl implements GMApplyRecordTService {
	
	private Logger log = Logger.getLogger(this.getClass().getName());

	@Autowired
	private PropertiesUtils propertiesUtils;

	@Resource
	private GMApplyRecordTDao gmApplyRecordTDao;

	@Resource
	private LoginDao loginDao;

	@Resource
	private DictionariesTDao dictionariesTDao;

	@Autowired
	private RedisClientUtils redisClientUtils;

	@Resource
	private RelationShipTDao relationShipTDao;

	@Resource
	private UserTDao userTDao;

	@Autowired
	private GMApplyService gmApplyService;
	
	
	@Autowired
	private CompanyTDao companyTDao;
	
	@Autowired
	private GMVisitorDao visitorDao;
	
	@Autowired
	private GMApplyRecordFlowService gMApplyRecordFlowService;
	
	@Autowired
	private MessagePushUtils messagePushUtils;
	
	@Autowired
	private ServiceStationDao serviceStationDao;
	
	

	//查看当前用户GM权限申请记录
	@Transactional
	@Override
	public ModelAndView getGMRecordList(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			int pageNum = MapUtils.getInteger(map,"pageNum",1);
			int pageCount = MapUtils.getInteger(map,"pageCount",20);
			String userId = AESTool.decryptString(request.getHeader("userid"));//解密userid
			UserT userT = loginDao.getUserByid(userId);
			JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
			PageHelper.startPage(pageNum,pageCount);
			List<Map<String,Object>> gmRecordList = gmApplyRecordTDao.getGMRecordList(userT.getId());
			PageInfo pageInfo = new PageInfo(gmRecordList);
			obj.put("status","0");
			obj.put("msg","success");
			obj.put("data",pageInfo.getList());
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}

	//查看当前用户GM权限申请记录详情
	@Transactional
	@Override
	public ModelAndView getGMApplyDetail(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			long recordId = MapUtils.getLong(map,"recordId");
			JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
			Map<String,Object> dataMap = new HashMap<>();
			Map<String,Object> gmApplyDetail = gmApplyRecordTDao.getGMApplyDetail(recordId);
			if(MapUtils.isNotEmpty(gmApplyDetail)){
				dataMap = gmApplyDetail;
			}
			List<Map<String,Object>> serviceLevelList= dictionariesTDao.getServiceLevelList();
			dataMap.put("serviceLevelList",serviceLevelList);
			obj.put("status","0");
			obj.put("msg","success");
			obj.put("data",dataMap);
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}


	//用户撤回申请
	@Transactional
	@Override
	public ModelAndView withdrawApply(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			long recordId = MapUtils.getLong(map,"recordId");
			Map<String,Object> updateMap = new HashMap<>();
			updateMap.put("ID",recordId);
			updateMap.put("Status",1); //0，待审核；1：已撤回；2：已审核；3：已拒绝；4：已解除；5：已过期
			String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间
			updateMap.put("WithdrawTime",currentTime);
			String userADId = AESTool.decryptString(request.getHeader("userid"));//解密userid
			UserT userT = loginDao.getUserByid(userADId);
			updateMap.put("Updator",userT.getId());
			updateMap.put("UpdateTime",currentTime);
			int result = gmApplyRecordTDao.updateGMApplyRecord(updateMap);
			JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
			obj.put("status","0");
			obj.put("msg","success");
			obj.put("data",result);
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}


	//用户提醒审核人
	@Transactional
	@Override
	public ModelAndView remindAudit(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间
		String userADId = AESTool.decryptString(request.getHeader("userid"));//解密userid
		UserT userT = loginDao.getUserByid(userADId);
		try{
			long recordId = MapUtils.getLong(map,"recordId");
			//若不存在于redis中，则无法提醒: status==2为今日已提醒；
			if (redisClientUtils.exists(RedisKeys.getRemindKey())){
				List<String> remindList = redisClientUtils.getList(RedisKeys.getRemindKey());
				if (remindList.size()>0){
                    if (!remindList.contains(String.valueOf(recordId))){
                        JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
                        obj.put("status","2");
                        obj.put("msg","您今日已经完成提醒");
                        obj.put("data","");
                        ParameterTool.writeResponse(response, obj.toString());
                        return null;
					}
				}
			} else {
				gmApplyService.setGMDailyStatus();
			}
			List<Map<String,Object>> remindAuditMsgList = gmApplyRecordTDao.getRemindAuditMsg(recordId);
			if(CollectionUtils.isNotEmpty(remindAuditMsgList)){
				for(Map<String,Object> remindAuditMsg : remindAuditMsgList){
					String applyUserName = MapUtils.getString(remindAuditMsg,"applyUserName","");  //真实姓名
					String applyUserPhone = MapUtils.getString(remindAuditMsg,"applyUserPhone","");
					String auditUserPhone = MapUtils.getString(remindAuditMsg,"auditUserPhone","");
					String auditUserName = MapUtils.getString(remindAuditMsg,"auditUserName","");  //用户名
					long auditUserId = MapUtils.getLongValue(remindAuditMsg,"auditUserId");
					String msg = "您收到一条Gudianz审批提醒，请尽快处理！申请人（姓名："+applyUserName+"； 手机号："+applyUserPhone+"）";
					if(StringUtils.isNotEmpty(auditUserPhone)){
						SmsUtils.sendMessage(auditUserPhone, msg);
					}
					if(StringUtils.isNotEmpty(auditUserName)){
						String clientId = redisClientUtils.hget(RedisKeys.geTuiKey(), auditUserName);
						if(StringUtils.isEmpty(clientId)) {
							// redis中不存在，查询数据库
							RelationShipT relationShipT = relationShipTDao.getClientIdByUserNameString(auditUserName);
							if(null != relationShipT){
								clientId = relationShipT.getClientId();
							}
						}
						// 发送推送操作
						NotifyUtil.push2Single(clientId, "Guidanz权限申请提醒", msg, 2, msg);
					}
					Map<String,Object> insertGMNotifyRecordData = new HashMap<>();
					insertGMNotifyRecordData.put("RecordId",recordId);
					insertGMNotifyRecordData.put("Type",1);   //消息类型：1，给审核人；2，给申请人
					insertGMNotifyRecordData.put("SendTime",currentTime);
					insertGMNotifyRecordData.put("ReceiverId",auditUserId);
					insertGMNotifyRecordData.put("MsgContent",msg);
					insertGMNotifyRecordData.put("IsRead",0);
					insertGMNotifyRecordData.put("Flag",0);
					insertGMNotifyRecordData.put("Creator",userT.getId());
					insertGMNotifyRecordData.put("CreateTime",currentTime);
					insertGMNotifyRecordData.put("SendType",0);
					int result = gmApplyRecordTDao.insertGMNotifyRecordData(insertGMNotifyRecordData);
				}
				JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
				obj.put("status","0");
				obj.put("msg","success");
				obj.put("data","");
				//删掉redis中每日提醒的recordId
				if (redisClientUtils.exists(RedisKeys.getRemindKey())){
					List<String> remindList = redisClientUtils.getList(RedisKeys.getRemindKey());
					if (remindList.contains(String.valueOf(recordId))){
						remindList.remove(String.valueOf(recordId));
						redisClientUtils.delkey(RedisKeys.getRemindKey());
						redisClientUtils.setList(RedisKeys.getRemindKey(),remindList,Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime")));
					}
				}
				ParameterTool.writeResponse(response, obj.toString());
			}
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}

	//GM权限管理列表接口
	@Transactional
	@Override
	public ModelAndView getGMApplyList(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			int type = MapUtils.getIntValue(map,"type");  //0：待审核数据；1：已授权数据；2：其他
			int pageNum = MapUtils.getIntValue(map,"pageNum",1);
			int pageCount = MapUtils.getIntValue(map,"pageCount",20);
			String userADId = AESTool.decryptString(request.getHeader("userid"));//解密userid
            UserT userT = loginDao.getUserByid(userADId);
            String status = "";  //申请状态
            if (type == 0) {
                status = "0";
            } else if (type == 1) {
                status = "2";
            } else {
                status = "1,3,4,5";
            }
            PageHelper.startPage(pageNum, pageCount);
            List<String> stringList = StringToool.getStringList(status, ",");
            List<Map<String, Object>> gmApplyList = gmApplyRecordTDao.getGMApplyList(stringList, userT.getId());
            PageInfo pageInfo = new PageInfo(gmApplyList);
            JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
            obj.put("status", "0");
            obj.put("msg", "success");
            obj.put("data", pageInfo.getList());
            ParameterTool.writeResponse(response, obj.toString());
        } catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}


	//拒绝申请接口
	@Transactional
	@Override
	public ModelAndView refuseApply(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间
		String userADId = AESTool.decryptString(request.getHeader("userid"));//解密userid
		UserT userT = loginDao.getUserByid(userADId);
		try{
			long recordId = MapUtils.getLong(map,"recordId");
			String reason = MapUtils.getString(map,"reason");
			Map<String,Object> updateMap = new HashMap<>();
			updateMap.put("Status",3);
			updateMap.put("HandlerId",userT.getId());
			updateMap.put("RefuseTime",currentTime);
			updateMap.put("RefuseReason",reason);
			updateMap.put("Updator",userT.getId());
			updateMap.put("UpdateTime",currentTime);
			updateMap.put("ID",recordId);
			gmApplyRecordTDao.updateGMApplyRecord(updateMap);
			List<Map<String,Object>> remindAuditMsgList = gmApplyRecordTDao.getRemindAuditMsg(recordId);
			if(CollectionUtils.isNotEmpty(remindAuditMsgList)){
				for(Map<String,Object> remindAuditMsg : remindAuditMsgList){
					long applyUserId = MapUtils.getLong(remindAuditMsg,"applyUserId");
					String applyUserName = MapUtils.getString(remindAuditMsg,"applyUserNames","");  //申请人用户名
					String applyUserPhone = MapUtils.getString(remindAuditMsg,"applyUserPhone","");  //申请人手机号
					String auditUserPhone = MapUtils.getString(remindAuditMsg,"auditUserPhone","");  //审核人手机号
					String msg = "您的Guidanz权限申请审核未通过，如有问题请联系审核人（手机号："+auditUserPhone+"）！";
					if(StringUtils.isNotEmpty(applyUserPhone)){
						SmsUtils.sendMessage(applyUserPhone, msg);
					}
					if(StringUtils.isNotEmpty(applyUserName)){
						String clientId = redisClientUtils.hget(RedisKeys.geTuiKey(), applyUserName);
						if(StringUtils.isEmpty(clientId)) {
							// redis中不存在，查询数据库
							RelationShipT relationShipT = relationShipTDao.getClientIdByUserNameString(applyUserName);
							if(null != relationShipT){
								clientId = relationShipT.getClientId();
							}
						}
						// 发送推送操作
						NotifyUtil.push2Single(clientId, "Guidanz权限申请提醒", msg, 2, msg);
					}
					Map<String,Object> insertGMNotifyRecordData = new HashMap<>();
					insertGMNotifyRecordData.put("RecordId",recordId);
					insertGMNotifyRecordData.put("Type",2);  //消息类型：1，给审核人；2，给申请人
					insertGMNotifyRecordData.put("SendTime",currentTime);
					insertGMNotifyRecordData.put("ReceiverId",applyUserId);
					insertGMNotifyRecordData.put("MsgContent",msg);
					insertGMNotifyRecordData.put("IsRead",0);
					insertGMNotifyRecordData.put("Flag",0);
					insertGMNotifyRecordData.put("Creator",userT.getId());
					insertGMNotifyRecordData.put("CreateTime",currentTime);
					insertGMNotifyRecordData.put("SendType",0);
					int result = gmApplyRecordTDao.insertGMNotifyRecordData(insertGMNotifyRecordData);
				}
			}
			JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
			obj.put("status","0");
			obj.put("msg","success");
			obj.put("data","");
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}


	//INSITE订单列表
	@Transactional
	@Override
	public ModelAndView getINSITEOrderList(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			String userId = AESTool.decryptString(request.getHeader("userid"));//解密userid
			UserT userT = loginDao.getUserByid(userId);
			Map<String,Object> userOrganizationType = userTDao.getUserOrganizationType(userT.getId());
			int organizationType = 0;   //组织类型
			long organizationId = 0;   //组织id
			if(MapUtils.isNotEmpty(userOrganizationType)){
				int isType = MapUtils.getIntValue(userOrganizationType,"IsType");
				if(isType == 1 || isType == 3){
					organizationType = 1;
					organizationId = MapUtils.getLongValue(userOrganizationType,"CompanyID");
				} else if(isType == 6){
					organizationType = 2;
					organizationId = MapUtils.getLongValue(userOrganizationType,"ServiceStationID");
				}
			}
			JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
			List<Map<String,Object>> serviceToolOrderList = gmApplyRecordTDao.getServiceToolOrderListByOrganizationTypeOrganizationId(organizationType,organizationId);
			obj.put("status","0");
			obj.put("msg","success");
			obj.put("data",serviceToolOrderList);
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}


	//GM权限申请消息列表
	@Transactional
	@Override
	public ModelAndView getGMMsgList(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			int pageNum = MapUtils.getInteger(map,"pageNum",1);
			int pageCount = MapUtils.getInteger(map,"pageCount",20);
			String userId = AESTool.decryptString(request.getHeader("userid"));//解密userid
			UserT userT = loginDao.getUserByid(userId);
			JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
			PageHelper.startPage(pageNum,pageCount);
			List<Map<String,Object>> gmMsgList = gmApplyRecordTDao.getGMMsgList(userT.getId());
			PageInfo pageInfo = new PageInfo(gmMsgList);
/*			String updateIds = "";   //获取到列表后    修改这页未读的消息状态，改为已读
			if(CollectionUtils.isNotEmpty(pageInfo.getList())){
				for(Object o : pageInfo.getList()){
					Map<String,Object> gmMsgMap = (Map<String, Object>) o;
					int isRead = MapUtils.getInteger(gmMsgMap,"isRead");
					if(isRead == 0){    //代表未读
						long id = MapUtils.getLongValue(gmMsgMap,"id");
						updateIds += id+",";
					}
				}
			}

			if(StringUtils.isNotEmpty(updateIds) && updateIds.endsWith(",")){
				updateIds = updateIds.substring(0,updateIds.length()-1);
				int updateNum = gmApplyRecordTDao.updateIsRead(updateIds);
			}*/

			obj.put("status","0");
			obj.put("msg","success");
			obj.put("data",pageInfo.getList());
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}

    @Override
    public ModelAndView updateGMMsgIsReadById(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse)map.get("response");
        HttpServletRequest request = (HttpServletRequest)map.get("request");
        String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间
        String userADId = AESTool.decryptString(request.getHeader("userid"));//解密userid
        UserT userT = loginDao.getUserByid(userADId);
        Integer id = MapUtils.getInteger(map, "ID");
        int con = gmApplyRecordTDao.updateGMMsgIsReadById(id,userT.getId(),currentTime);
        ParameterTool.writeSuccessResponse(response);
        return null;
    }
    
    
    
    
    /**
     * 获取用户的GM权限
     */
    @Override
    public void getUserGMLevel(Map<String, Object> map) {
    	HttpServletResponse response = (HttpServletResponse)map.get("response");
    	// 获取当前用户
    	UserT user = UserThreadLocal.get();
    	
    	/**
    	 * 校验当前用户是否已存在访客身份，如果没有则授权当前用户为Guidanz访客身份
    	 */
    	Long userId = user.getId();
    	if(visitorDao.countByUserId(userId) <= 0) {
    		// 如果当前用户没有访客角色，自动添加一个访客角色
    		visitorDao.insertSelective(new GMVisitorEntity(userId, userId, LocalTimeUtil.getRealCurrentTime()));
    	}
    	
    	
		try {
			String username = user.getUserName();
			Integer type = user.getType();
			String unionId = (2 == type.intValue() ? username : "8" + String.format("%08d", userId));
			((GMApplyServiceImpl)gmApplyService).updateADCustomerAttributes(username, type, unionId, null, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	
    	Map<String,Object> result = new HashMap<>();
    	result.put("isGuidanzUser", 1);
	
    	// 查询出当前用户审核通过的权限
    	Map<String, Object> userGMLevel = gmApplyRecordTDao.getUserGMLevelByUserId(user.getId());
    	
    	log.info("用户拥有的GM权限：" + userGMLevel);
    	
    	Set<String> levels = new HashSet<>();
    	if(userGMLevel != null) {
    		
    		// 用户申请的权限
    		//String serviceType = MapUtils.getString(userGMLevel, "ServiceType");
    		
    		// 当前字段表示用户此时所拥有的未解除的权限，用户拥有的多个权限其中几个可能会被解除
    		String serviceType = MapUtils.getString(userGMLevel, "ServiceUptodateType");
    		
    		//serviceType = serviceUptodateType;
    		
    		// serviceTypes可以为空，因为用户在申请GM权限时，可以只申请某些权限的次数，而不用申请具体的权限
    		if(StringUtils.isNotEmpty(serviceType)) {
	    		// 过滤出当前用户未过期的权限
	    		String[]  levelArr = serviceType.split(",");
	    		levels = Arrays.stream(levelArr).collect(Collectors.toSet());
	    		
	    		GuidanzLevel[] levelEnum = GuidanzLevel.values();
	    		for(int i=0; i< levelEnum.length; i++) {
	    			GuidanzLevel guidanzLevel = levelEnum[i];
	    			// 校验当前用户是否包含这个GM级别，如果包含然后校验是否过期
	    		    if(levels.contains(guidanzLevel.getCode())) {
	    		    	switch (guidanzLevel) {
	    				case IAS0:
	    					checkGMLevelIsExpire(levels, GuidanzLevel.IAS0.getCode(), userGMLevel, "IAExpireDate");
	    					break;
	    				case SRV0:
	    					checkGMLevelIsExpire(levels, GuidanzLevel.SRV0.getCode(), userGMLevel, "SRVExpireDate");
	    					break;
	    				case CMP0:
	    					checkGMLevelIsExpire(levels, GuidanzLevel.CMP0.getCode(), userGMLevel, "CMPExpireDate");
	    					break;
	    				case BTGF:
	    					checkGMLevelIsExpire(levels, GuidanzLevel.BTGF.getCode(), userGMLevel, "BTGFExpireDate");
	    					break;
	    				default:
	    					break;
	    				}
	    		    	
	    		    }
	    		}
    		}
	    	result.put("levels", levels);
    	}
    	ParameterTool.writeSuccessResponse(response, result);
    }
    
    
    /**
     * 校验GM权限是否过期
     */
    private void checkGMLevelIsExpire(Set<String> levels, String level, Map<String, Object> userGMLevel, String key) {
			String expireDate = MapUtils.getString(userGMLevel, key);
			if(StringUtils.isEmpty(expireDate)) {
				expireDate = MapUtils.getString(userGMLevel, "ExpireDate");
			}
			if(LocalTimeUtil.isExpired(expireDate)) {
				levels.remove(level);
			}
    }
    
    
    private enum GuidanzLevel {
    	IAS0("IAS0", "数据同步"),
    	SRV0("SRV0", "服务功能"),
    	// 这个级别在新系统作废
    	CMP0("CMP0", "标定统修"),
    	BTGF("BTGF", "Beta订阅");
    	
       private String code;
       
       private String desc;
       
       GuidanzLevel(String code, String desc){
    	   this.code = code;
    	   this.desc = desc;
       }
       
       public String getCode() {
    	   return this.code;
       }
       
       public String getDesc() {
    	   return this.desc;
       }
    }
    
    
    
    /**
     * Guidanz需求
     * 渠道列表
     */
	@Override
	public void getCompanyList(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		List<CompanyT> companyList = companyTDao.getCompanyList();
		
		if(CollectionUtils.isNotEmpty(companyList)) {
			for(CompanyT e : companyList) {
				
				String companyNo = e.getCompanyNo();
				 if(Objects.equals(companyNo, "BFCEC")) {
					 e.setCompanyName("福田渠道");
				 }
			}
		}
		
		ParameterTool.writeSuccessResponse(response, companyList);
	}

    /**
     * Guidanz需求
     * 渠道对应的服务站列表
     */
	@Override
	public void getServiceStationByCompanyId(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		int pageNum = MapUtils.getIntValue(map, "page", 1);
		int pageCount = MapUtils.getIntValue(map, "pageSize", 20);
		Long companyId = MapUtils.getLong(map, "companyId");
		String keywords = MapUtils.getString(map, "keywords");
		
		// 增加了分公司的查询 companyType=
		int companyType = MapUtils.getIntValue(map, "companyType", -1);
		
		if(null == companyId) {
			ParameterTool.writeResponse(response, -5, "companyId不能为空");
		}
		
		PageInfo<Map<String, Object>> pageInfo = null;
		if(companyType != 1) {
			// 查询服务站
			pageInfo = PageHelper.startPage(pageNum,pageCount)
			              .<Map<String, Object>>doSelectPageInfo(() -> companyTDao.getServiceStationByCompanyId(companyId, keywords));
		} else {
			// 查询分公司
			pageInfo = PageHelper.startPage(pageNum,pageCount)
		              .<Map<String, Object>>doSelectPageInfo(() -> companyTDao.getSubServiceStationByCompanyId(companyId, keywords));
		}
		
		Map<String, Object> result = new HashMap<>();
		result.put("page", pageInfo.getPageNum());
		result.put("pageSize", pageInfo.getPageSize());
		result.put("total", pageInfo.getTotal());
		result.put("list", pageInfo.getList());
		
		ParameterTool.writeSuccessResponse(response, result);
	}
    
	
	
	
	/**
	 * 申请Guidanz权限
	 */
	@Override
	@Transactional
	public void applyLevels(Map<String, Object> map) {
			applyLevels(map, (recordMap, recordStatus, currentTime) -> {
				gmApplyRecordTDao.insertSelectiveNew(recordMap);
				// 保存流水
				gMApplyRecordFlowService.saveApplyRecordFlow(MapUtils.getLong(recordMap, "ID"),
															 recordStatus.getStatus(),
															 recordStatus.getDesc(),
															 MapUtils.getLong(recordMap, "CompanyId")	,
															 MapUtils.getLong(recordMap, "ServiceStationId"),
															 MapUtils.getLong(recordMap, "UserId"),
															 currentTime);
			});
    	
    	
	}
	
	
	
	
	
	private void applyLevels(Map<String, Object> map, Action action) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		
		// 当前用户
		UserT user = UserThreadLocal.get();
		
		// 获取email参数校验当前email在数据库中是否已存在
		String email = MapUtils.getString(map, "email");
		if(StringUtils.isNotEmpty(email)) {
			// 如果不相等说明用户修改了email
			if(!email.equals(user.getEmail())) {
				// 当用户修改了邮箱时，需要校验数据库中是否已存在重复的email
				int count = userTDao.countByEmail(email, user.getId());
				if(count > 0) {
					ParameterTool.writeResponse(response, 5, "邮箱已注册");
					return;
				}else {
					userTDao.updateEmailByUserId(email, user.getId());
				}
			}
		}else {
			// 清空帐号的邮箱
			if(StringUtils.isNotEmpty(user.getEmail())) {
				userTDao.updateEmailByUserId(email, user.getId());
			}
		}
		
		
		String currentTime = LocalTimeUtil.getRealCurrentTime();
		String serviceType = MapUtils.getString(map, "serviceType");
	
		if(StringUtils.isNotEmpty(serviceType)) {
			// 权限默认的过期时间为1年
			String expireDate = LocalTimeUtil.getCurrentDateAddYears(1);
			
			map.put("expireDate", expireDate);
			Set<String> levelSet = Arrays.stream(serviceType.split(",")).collect(Collectors.toSet());
			if(levelSet.contains(GuidanzLevel.IAS0.getCode())) map.put("iAExpireDate", expireDate);
			if(levelSet.contains(GuidanzLevel.SRV0.getCode())) map.put("sRVExpireDate", expireDate);
		}
		
		GMApplyRecordStatus recordStatus = null;
		List<String> hasRoles = userTDao.getUserHasRolesByUserID(user.getId());
		/**
		 * 服务商站长	 R0041
		 * 服务商信息员	 R0069
		 * 服务技师	     R0033
		 * 服务商信息员、服务技师申请的权限状态为站长审核中
		 */
		int companyType = MapUtils.getIntValue(map, "companyType", 1);
		if(hasRoles != null && (!hasRoles.contains("R0041") && (companyType == 2) && (hasRoles.contains("R0033") || hasRoles.contains("R0069")))) {
			// 站长审核中
			recordStatus = GMApplyRecordStatus.STATION_AUDIT;
			
		}else {
			// 管理员审核中
			recordStatus = GMApplyRecordStatus.ADMIN_AUDIT;
		}
		
		map.put("status", recordStatus.getStatus());
		
		
		// 生成申请单 	
		Map<String, Object> applyRecordMap = createApplyRecord(map, user.getId(), currentTime);
		
		
		// 修改其它处于审核中的的带级别的申请单为撤消状态
		// 特别说明：只申请了计次的申请单，允许存在多个待审核状态的;  申请了带级别的申请单不允许存在多个待审核状态的;
	    // recordType参数说明：0表示当前用户申请了级别(也可能有计次),1表示当前用户只申请了计次
		int recordType = MapUtils.getIntValue(map, "recordType", -1);
		if(recordType == 0) {
			/**
			 * 1.查询出当前用户处于审核中的申请单(只包含带权限级别的申请单)
			 * 2.并将其修改成撤消状态
			 */
			List<Map<String, Object>> auditApplyRecordList = gmApplyRecordTDao.getAuditApplyRecordsByUserId(user.getId());
			
			// 将申请单置为撤消状态
			if(CollectionUtils.isNotEmpty(auditApplyRecordList)) {
				
				log.info("撤销当前用户的权限申请单(站长或管理员审核中)");
				
				for(Map<String, Object> auditRecord : auditApplyRecordList) {
					// 在撤消申请单时，如果申请单状态还是(站长审核中、管理员审核中)则撤消，否则不撤消
					Long recordId = MapUtils.getLong(auditRecord, "ID");
					Map<String, Object> updateMap = new HashMap<>();
					updateMap.put("recordId", recordId);
					updateMap.put("status", GMApplyRecordStatus.USER_WITHDRAW.getStatus());
					updateMap.put("updator", user.getId());
					updateMap.put("updateTime", currentTime);
					int result = gmApplyRecordTDao.doWithdrawApplyRecordById(updateMap);
					
					int applySource = MapUtils.getIntValue(auditRecord, "ApplySource", 0);
					// 当前申请单是由Guidanz-App所申请，那么需要对当前申请单生成流水
					// 旧系统申请的权限单，目前不生成流水
					if(result > 0 && applySource == 1) {
						log.info(String.format("ID：%s 生成操作流水", recordId));
						// 查询出最新的操作流水
						Map<String, Object>  recordFlow = gMApplyRecordFlowService.getNewestApplyRecordFlowByRecordId(recordId);
						// recordFlow正常情况不会为空
						if(recordFlow != null) {
							recordFlow.put("ApplyRecordStatus", GMApplyRecordStatus.USER_WITHDRAW.getStatus());
							recordFlow.put("Description", GMApplyRecordStatus.USER_WITHDRAW.getDesc());
							recordFlow.put("Remark", "用户申请新的权限，旧的权限被撤销");
							recordFlow.put("Creator", user.getId());
							recordFlow.put("CreateTime", currentTime);
							gMApplyRecordFlowService.saveApplyRecordFlow(recordFlow);
						}
					}
					
				}
			}
			
		}
		
		
		action.action(applyRecordMap, recordStatus, currentTime);
		
		// 给审核人推送消息
		// 新增权限的时候需要消息推送，编辑权限时间不推送消息
		Long recordId = MapUtils.getLong(map, "recordId");
		if(recordId == null) {
			try {
				messagePushUtils.pushMessageToAuditorForGuidanz(recordStatus,
																MapUtils.getLong(applyRecordMap, "ID"),
															    MapUtils.getLong(map, "companyId"),
															    MapUtils.getLong(map, "serviceStationId"),
															    MapUtils.getLong(map, "subServiceStationId"),
															    user.getId(),
																user.getContact(), 
																user.getPhone());
			} catch (Exception e) {
				log.error("消息推送异常 原因：" + e.getMessage());
			}
		}
		
		ParameterTool.writeSuccessResponse(response);
	}
	
	
	
	
	
	
	
	
	@FunctionalInterface
	private interface Action {
		
		void action(Map<String, Object> recordMap, GMApplyRecordStatus recordStatus, String currentTime);
		
	}
	
	
	 
	 
	@Override
	@Transactional
	public void userUpdateApplyRecord(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		
		// 解决前端参数传递的问题
		int hasCalAssit = MapUtils.getIntValue(map, "hasCalAssit", -1);
		if(hasCalAssit == 1) {
			Integer calAssitApproveTimes = MapUtils.getInteger(map, "calAssitApproveTimes");
			map.put("calAssitTimes", calAssitApproveTimes);
		}
		
		int hasIntApp = MapUtils.getIntValue(map, "hasIntApp", -1);
		if(hasIntApp == 1) {
			Integer intAppApproveTimes = MapUtils.getInteger(map, "intAppApproveTimes");
			map.put("intAppTimes", intAppApproveTimes);
		}
		
		
		try {
			applyLevels(map, (recordMap, recordStatus, currentTime) -> {
				recordMap.remove("UserId");
				recordMap.remove("Creator");
				recordMap.remove("CreateTime");

				int count = gmApplyRecordTDao.updateApplyRecordServiceTypeByIdAndVersion(recordMap);
				
				// 修改成功后增加操作流水
				if (count > 0) {
					Map<String, Object> flowMap = gMApplyRecordFlowService
							.getNewestApplyRecordFlowByRecordId(MapUtils.getLong(recordMap, "ID"));

					/**
					 * 理论上此时的flowMap不为空
					 */
					if (flowMap == null) {
						flowMap = new HashMap<>(8);
					}

					flowMap.put("ApplyRecordID", recordMap.get("ID"));
					flowMap.put("ApplyRecordStatus", recordStatus.getStatus());
					flowMap.put("Description", recordStatus.getDesc());
					flowMap.put("CompanyID", recordMap.get("CompanyId"));
					flowMap.put("ServiceStationID", recordMap.get("ServiceStationId"));
					flowMap.put("RoundTimes", MapUtils.getIntValue(flowMap, "RoundTimes", -1) + 1);
					flowMap.put("Creator", recordMap.get("Updator"));
					flowMap.put("CreateTime", currentTime);

					// 保存流水
					gMApplyRecordFlowService.saveApplyRecordFlow(flowMap);

				} else {
					throw new StatusUpdateFailException(-10, "修改失败,申请单状态已改变");
				}
			});
		} catch (StatusUpdateFailException e) {
			ParameterTool.writeResponse(response, e.getCode(), e.getMessage());
		}
		
	}
	
	
	static class StatusUpdateFailException extends RuntimeException {
		
		private static final long serialVersionUID = 1L;
		
		private int code;
		
		public StatusUpdateFailException(int code, String msg) {
			super(msg);
			this.code = code;
		}

		public int getCode() {
			return code;
		}
		
		
	}
	
	
	
	private Map<String, Object> createApplyRecord(Map<String, Object> map,Long userId, String currentTime) {
		Map<String, Object> applyRecord = new HashMap<>();
		applyRecord.put("ID", map.get("recordId"));
		applyRecord.put("UserId",userId);
		applyRecord.put("CompanyId",map.get("companyId"));
		applyRecord.put("CompanyNo",map.get("companyNo"));
		applyRecord.put("CompanyName",map.get("companyName"));
		
		applyRecord.put("CompanyType",MapUtils.getIntValue(map, "companyType", 1));
		
		String serviceType = MapUtils.getString(map, "serviceType", "");
		applyRecord.put("ServiceType", serviceType);
		applyRecord.put("ServiceUptodateType", serviceType);
		
		applyRecord.put("ApplyTime",currentTime);
		applyRecord.put("ExpireDate",map.get("expireDate"));
		applyRecord.put("Status",map.get("status"));
		applyRecord.put("AuthorizeTime",map.get("authorizeTime"));
		applyRecord.put("Creator", userId);
		applyRecord.put("CreateTime",currentTime);
		
		applyRecord.put("Updator", userId);
		applyRecord.put("UpdateTime",currentTime);
		
		
		//applyRecord.put("ApplyRecordNo",SerialNumberUtil.getGMApplyRecordNumber("GM"));
		
		applyRecord.put("IAExpireDate", map.get("iAExpireDate"));
		applyRecord.put("SRVExpireDate", map.get("sRVExpireDate"));
		
		int hasCalAssit = MapUtils.getIntValue(map, "hasCalAssit", 0);
		
		applyRecord.put("HasCalAssit", hasCalAssit);
		if(hasCalAssit == 1) {
			applyRecord.put("CalAssitTimes", map.get("calAssitTimes"));
			applyRecord.put("CalAssitApproveTimes", map.get("calAssitTimes"));
		}else {
			applyRecord.put("CalAssitTimes", 0);
			applyRecord.put("CalAssitApproveTimes", 0);
		}
		
		
		int hasIntApp = MapUtils.getIntValue(map, "hasIntApp", 0);
		
		applyRecord.put("HasIntApp", hasIntApp);
		if(hasIntApp == 1) {
			applyRecord.put("IntAppTimes", map.get("intAppTimes"));
			applyRecord.put("IntAppApproveTimes", map.get("intAppTimes"));
		}else {
			applyRecord.put("IntAppTimes", 0);
			applyRecord.put("IntAppApproveTimes", 0);
		}
		
		/**
		 * ApplySource 参数说明：
		 * 0：表示来自旧系统的申请
		 * 1：表示来自Guidanz-H5的申请
		 */
		applyRecord.put("ApplySource",1);
		applyRecord.put("HadGMLevel",map.get("hadGMLevel"));
		applyRecord.put("UserType", map.get("userType"));
		applyRecord.put("ServiceStationId", map.get("serviceStationId"));
		applyRecord.put("ServiceStationName", map.get("serviceStationName"));
		
		applyRecord.put("SubServiceStationId", map.get("subServiceStationId"));
		applyRecord.put("SubServiceStationName", map.get("subServiceStationName"));
		
		// recordType说明： 0表示当前申请单包含了级别  1表示当前申请单只包含计次
		// applyRecord.put("RecordType", map.get("recordType"));
		applyRecord.put("RecordType", StringUtils.isEmpty(serviceType) ? 1 : 0);
		
		applyRecord.put("Version", map.get("version"));
		
		return applyRecord;
	}
	
	
	/**
	 * 撤回Guidanz权限
	 */
	@Override
	@Transactional
	public void withdrawApplyRecord(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		
		UserT user = UserThreadLocal.get();
		
		String currentTime = LocalTimeUtil.getRealCurrentTime();
		Map<String, Object> param = new HashMap<>();
		Long recordId = MapUtils.getLong(map, "id");
		param.put("recordId", recordId);
		param.put("version", MapUtils.getLong(map, "version"));
		param.put("status", GMApplyRecordStatus.USER_WITHDRAW.getStatus());
		param.put("withdrawTime", currentTime);
		param.put("updator", user.getId());
		param.put("updateTime", currentTime);
		
		int count = gmApplyRecordTDao.updateApplyRecordStatus(param);
		if(count > 0) {
			// 获取当前申请单最新的操作流水
			Map<String, Object> applyRecordFlow = gMApplyRecordFlowService.getNewestApplyRecordFlowByRecordId(recordId); 
			// 保存操作流水
			gMApplyRecordFlowService.saveApplyRecordFlow(recordId, 
														 GMApplyRecordStatus.USER_WITHDRAW.getStatus(), 
														 GMApplyRecordStatus.USER_WITHDRAW.getDesc(), 
														 MapUtils.getLong(applyRecordFlow, "CompanyID"),
														 MapUtils.getLong(applyRecordFlow, "ServiceStationID"),
														 user.getId(), 
														 currentTime, 
														 MapUtils.getInteger(applyRecordFlow, "RoundTimes"));
			ParameterTool.writeSuccessResponse(response);
		}else {
			ParameterTool.writeResponse(response, 50, "撤回失败,记录状态已改变，请刷新");
		}
	}
	
	/**
	 * Guidanz权限
	 */
	@Override
	public void applyRecordList(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		
		Integer page = MapUtils.getInteger(map, "page", 1);
		Integer pageSize = MapUtils.getInteger(map, "pageSize", 20);
		
		UserT user = UserThreadLocal.get();
		PageInfo<Object> pageInfo = PageHelper.startPage(page, pageSize).doSelectPageInfo(() -> gmApplyRecordTDao.getGMRecordListNew(user.getId()));
		
		Map<String, Object> result = new HashMap<>();
		result.put("page", page);
		result.put("pageSize", pageSize);
		result.put("total", pageInfo.getTotal());
		result.put("list", pageInfo.getList());
		ParameterTool.writeSuccessResponse(response, result);
	}
	
	@Override
	public void applyRecordDetail(Map<String, Object> map) {
		
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		Long id = MapUtils.getLong(map, "id");
		Map<String, Object> applyRecordDetail = gmApplyRecordTDao.applyRecordDetail(id);
		ParameterTool.writeSuccessResponse(response, applyRecordDetail);
	}
	
	@Override
	public void stationAuditList(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		/**
		 * type = 0 表示：待审核列表
		 * type = 1 表示：已审核列表
		 */
		int type = MapUtils.getIntValue(map, "type", -1);
		int page = MapUtils.getIntValue(map, "page", 1);
		int pageSize = MapUtils.getIntValue(map, "pageSize", 10);
		
		if(type == -1) {
			ParameterTool.writeResponse(response,-5 , "参数不能为空");
			return;
		}
		
		/**
		 * 获取当前用户的服务站ID
		 */
		long serviceStationID = UserThreadLocal.get().getServiceStationID();
		
		/**
		 *  type	0：待审核列表  1：已审核列表
		 *  不同的列表查询不同的状态
		 *  状态说明:
		 * 	6: 站长审核中
		 *  0: 管理员审核中
		 *  2: 管理员审核通过
		 *  3: 管理员驳回
		 *  7: 站长驳回              
		 */
		List<Integer> recordStatus = (type == 0 ? Arrays.asList(6) : Arrays.asList(0, 2, 3, 7, 4));
	
		
		PageInfo<Map<String, Object>> info = PageHelper.startPage(page, pageSize)
		          								       .<Map<String, Object>>doSelectPageInfo(
		          								    		   () -> gmApplyRecordTDao.stationAuditList(serviceStationID, recordStatus, type));
		
		Map<String, Object> result = new HashMap<>(4);
		result.put("page", info.getPageNum());
		result.put("pageSize", info.getPageSize());
		result.put("total", info.getTotal());
		result.put("list", info.getList());
		
		ParameterTool.writeSuccessResponse(response, result);
	}
	
	@Override
	@Transactional
	public void stationApproveOrRefuseRecord(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		// 申请单ID
		Long recordId = MapUtils.getLong(map, "recordId");
		// 1: 站长审核通过   0：站长驳回
		int isApprove = MapUtils.getIntValue(map, "isApprove", -1);
		int version = MapUtils.getIntValue(map, "version", -1);
		// 驳回原因
		String refuseReason = MapUtils.getString(map, "refuseReason");
		
		if(-1 == isApprove || -1 == version || null == recordId) {
			ParameterTool.writeResponse(response, -5, "参数不能为空");
			return;
		}
		
		if(isApprove != 0 && isApprove != 1) {
			ParameterTool.writeResponse(response, -6, "参数值错误");
			return;
		}
		
		
		UserT user = UserThreadLocal.get();
		String currentDate = LocalTimeUtil.getRealCurrentTime();
		
		
		GMApplyRecordStatus recordStatus = GMApplyRecordStatus.STATION_REFUSE;
		if(isApprove == 1) {
			recordStatus = GMApplyRecordStatus.ADMIN_AUDIT;
		}
		
		
		Map<String, Object> updateRecord = new HashMap<>();
		updateRecord.put("ID", recordId);
		updateRecord.put("Version", version);
		updateRecord.put("Status", recordStatus.getStatus());
		updateRecord.put("Updator", user.getId());
		updateRecord.put("UpdateTime", currentDate);
		
		if(isApprove == 0) {
			updateRecord.put("RefuseTime", currentDate);
			updateRecord.put("RefuseReason", refuseReason);
		}
		
		
		/**
		 * 更新申请单状态
		 */
		int result = gmApplyRecordTDao.updateApplyRecordByIdAndVersion(updateRecord);
		
		if(result > 0) {
			// 查询出当前申请单最新的操作流水
			Map<String, Object> flowMap = gMApplyRecordFlowService.getNewestApplyRecordFlowByRecordId(recordId);
			if(flowMap == null) {
				flowMap = new HashMap<>(8);
			}
			
			flowMap.put("ApplyRecordID", recordId);
			flowMap.put("ApplyRecordStatus", recordStatus.getStatus());
			flowMap.put("Description", recordStatus.getDesc());
			flowMap.put("CompanyID", map.get("companyId"));
			flowMap.put("ServiceStationID", map.get("serviceStationId"));
			flowMap.put("Remark", refuseReason);
			flowMap.put("Creator", user.getId());
			flowMap.put("CreateTime", currentDate);
			
			// 生成操作流水
			gMApplyRecordFlowService.saveApplyRecordFlow(flowMap);
			
			// 当申请单被驳回后推送消息给用户
			// isApprove 1: 站长审核通过   0：站长驳回
			try {
				if(isApprove == 0) {
					
					messagePushUtils.pushRejectMsgToUserForGuidanz(recordId, user.getId());
				}else {
					
					Map<String, Object> applyRecordDetail = gmApplyRecordTDao.applyRecordDetail(recordId);
					
					messagePushUtils.pushMessageToAuditorForGuidanz(recordStatus, 
																	recordId, 
																	MapUtils.getLong(applyRecordDetail, "companyId"), 
																	null,
																	MapUtils.getLong(applyRecordDetail, "subServiceStationId"),
																	user.getId(), 
																	MapUtils.getString(applyRecordDetail, "contact"),
																	MapUtils.getString(applyRecordDetail, "phone"));
				}
			} catch (Exception e) {
				log.error("消息推送异常 原因：" + e.getMessage());
			}
			
			
			ParameterTool.writeSuccessResponse(response);
			return;
		}
		
		ParameterTool.writeResponse(response, -10, "更新失败，当前申请单状态已改变");
		return;
		
	}
	
	
	@Override
	public void getSubstationList(Map<String, Object> map) {
		
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		
		int page = MapUtils.getIntValue(map, "page", 1);
		int pageSize = MapUtils.getIntValue(map, "pageSize", 20);
		String keywords = MapUtils.getString(map, "keywords");
		
		PageInfo<Map<String, Object>> pageInfo = PageHelper.startPage(page, pageSize)
												           .doSelectPageInfo(() -> {
												        	   	serviceStationDao.getSubstationList(keywords);
												           });
		
		
		Map<String, Object> result = new HashMap<>();
		result.put("page", pageInfo.getPageNum());
		result.put("pageSize", pageInfo.getPageSize());
		result.put("total", pageInfo.getTotal());
		result.put("list", pageInfo.getList());
		
		ParameterTool.writeSuccessResponse(response, result);
		
	}
	
	
}
